package net.wanho.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class LogAdvice {

    /**
     * 定义切入点
     */
    @Pointcut("execution(* net.wanho.service.impl.*ServiceImpl.*(..))")
    public void pc(){

    }

    /**
     * 前置通知
     */
    @Before("pc()")
    public void before(JoinPoint joinPoint){ // 连接点
        System.out.println("在方法执行前做日志。。。。。。。方法名：" + joinPoint.getSignature().getName() + "，参数：" + Arrays.toString(joinPoint.getArgs()));
    }

    /**
     * 后置通知
     */
    @AfterReturning(value = "pc()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result){
        System.out.println("在方法执行后做日志。。。。。。。方法名：" + joinPoint.getSignature().getName() + "，参数：" + Arrays.toString(joinPoint.getArgs()) + "，返回值：" + result);
    }

    /**
     * 异常通知
     */
    @AfterThrowing(value = "pc()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e){
        System.out.println("在方法出现异常时做日志。。。。。。。方法名：" + joinPoint.getSignature().getName() +  "，异常信息：" + e.getMessage());
    }

    /**
     * 环绕通知
     */
    @Around("pc()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("在方法执行前开启事务。。。。。。。。。。。");

        // 执行方法
        try {
            Object value = joinPoint.proceed();
            System.out.println("在方法执行后提交事务。。。。。。。。。。。");
            return value;
        } catch (Throwable e) {
            System.out.println("在方法执行后回滚事务。。。。。。。。。。。");
            throw new RuntimeException(e);
        }
    }

}
